<?php
/**
 * 
 * OrderAction.class.php (前台购物订单)
 *
 * @package      	jgsat
 * @author          liuxun QQ:147613338 <admin@jgsat.cn>
 * @copyright     	Copyright (c) 2008-2011  (http://www.jgsat.com)
 * @license         http://www.jgsat.com/license.txt
 * @version        	jgsat企业网站管理系统 v2.1 2011-03-01 jgsat.cn $
 */
if(!defined("JGsat")) exit("Access Denied");
class OrderAction extends BaseAction
{
	protected   $dao , $sessionid;
	function _initialize()
    {
		parent::_initialize();
		$this->dao=M('Cart');
		$this->sessionid =  cookie('onlineid');
    }


    public function index()
    {	
        $pcatid=intval($_GET["pcid"]);
        if($pcatid==0){
            $pcatid=143;
        }
        $procat=$this->categorys[$pcatid];
        $this->assign('procat',$procat);
        $prodatacatid=$procat["arrchildid"];
        $this->assign('prodatacatid',$prodatacatid);
        
        $spcatid=intval($_GET["spcid"]);
        if($spcatid>0){
            $sprocat=$this->categorys[$spcatid];
            $this->assign('sprocat',$sprocat);
            $prodatacatid=$sprocat["arrchildid"];
            $this->assign('prodatacatid',$prodatacatid);
        }
        
        
        $buy = intval($_REQUEST['buy']);
        $cart = $this->dao->where("sessionid='{$this->sessionid}'")->select();
        
        $buyproidlist=",";
        foreach($cart as $k=>$r){
                $buyproidlist.=$r["product_id"].",";
        }
        
        $prolist=M("Product")->where("catid in (".$prodatacatid.")")->select();
        foreach($prolist as $k=>$r){
            $sproid=",".$r["id"].",";
            if($buyproidlist!=","){
                if(substr($buyproidlist,$sproid)){
                    $prolist[$k]["issel"]=1;
                }
                else{
                    $prolist[$k]["issel"]=0;
                }
            }
        }
        if($this->_userid){
            $user=M("User")->find($this->_userid);
            $this->assign('usi',$user);
        }
        $this->assign('prolist',$prolist);
        $this->assign('cart',$cart);
        $this->display();
    }

	public function checkout(){

		if($this->Config['isuserbuy'] && empty($this->_userid))$this->error ( L('do_empty'));

		$data= M()->query("SELECT DISTINCT o.sessionid FROM ".C('DB_PREFIX')."cart as c , ".C('DB_PREFIX')."online as o where c.sessionid=o.sessionid ");
		if($data){
			foreach($data as $key=>$id)$ids[]=$id['sessionid'];
			M('Cart')->where(" sessionid NOT in('".implode("','",$ids)."') ")->delete();
		}

		$cart = $this->dao->where("sessionid='{$this->sessionid}'")->select();
		$amount=0;
		foreach($cart as $key=>$r){
			$amount = $amount+$r['price'];
		}

		$this->assign('cart',$cart);
		$this->assign('buy',1);

		if($this->_userid)
			$user_address = M('User_address')->where("userid='{$this->_userid}'")->select();
		else
			if( cookie('guest_address'))$default_address = unserialize( cookie('guest_address'));

		$Area = M('Area')->getField('id,name');
		$shipping = M('Shipping')->where("status=1")->select();
		$payment = M('Payment')->field('id,pay_code,pay_name,pay_fee,pay_fee_type,pay_desc,is_cod,is_online')->where("status=1")->select();

		foreach($user_address as $key=>$r){
			if($r['isdefault'])$default_address=$r;
		}
		$this->assign('default_address',$default_address);
		$this->assign('payment',$payment);
		$this->assign('user_address',$user_address);
		$this->assign('Area',$Area);
		$this->assign('shipping',$shipping);

		if($_REQUEST['do']){
			$this->assign('buy',2);
		}
	    $this->display();
	}

	public function _before_insert(){
		$_POST['ip'] = get_client_ip();
	}

	public function ajax(){ 
		$id = intval($_REQUEST['id']);
		$num = intval($_REQUEST['num']);
		$moduleid = intval($_REQUEST['moduleid']);
		$module =  $this->module[$moduleid]['name'];
		$do = $_REQUEST['do']; 
		
		if($do=='add'){
			if(!$module){$res['msg']='error';echo json_encode($res); exit;}	
			$session_info = M('Online')->find($this->sessionid);
			$r=M($module)->find($id);
			$cart = $this->dao->where("product_id='{$id}' and sessionid='{$this->sessionid}'")->find();
			if($cart){
				$cart['number']=$cart['number']+$num;
				$cart['price'] = $cart['product_price']*$cart['number'];
				$rs = $this->dao->save($cart);
			}else{
				$data=array();
				$data['userid']=$session_info['userid'];
				$data['sessionid']=$session_info['sessionid'];
				$data['product_id']=$r['id'];
				$data['product_thumb']=$r['thumb'];
				$data['product_url']=$r['url'];
				$data['product_name']=$r['title'];
				$data['product_price'] =$r['price'];
				$data['product_yhinfo'] =$r['yhinfo'];
				$data['moduleid']=$moduleid;	
				$data['number']=$num;
				$data['price']= $data['product_price']*$data['number'];
				$rs = $this->dao->add($data);
			}
			
			$res['data']= $rs ? 1 : 0 ;
			echo json_encode($res); exit;		
		}elseif($do=='update'){
			$data = $this->dao->find($id);
			$data['number']=$num;
			$data['price']=$data['product_price']*$data['number'];
			$rs = $this->dao->save($data);
			$res['data']= $rs ? 1 : 0 ;
			echo json_encode($res); exit;
		}elseif($do=='del'){
			$rs = $this->dao->delete($id);
			$res['data']= $rs ? 1 : 0 ;
			echo json_encode($res); exit;
		} 
 
	}
	public function clear(){
		$this->dao->where("sessionid = '$this->sessionid'")->delete();
		$this->error ( L('do_ok'));
	}
        public function reguser(){
            $mobile = get_safe_replace($_POST['mobile']);
            $email = get_safe_replace($_POST['email']);
            if(empty($mobile)){
                $this->error("我的信息中手机号码不能为空！");
            }
            if(empty($email)){
                $this->error("我的信息中邮箱Email不能为空！");
            }
            if(isset($_POST['isreg']) && !empty($_POST['isreg'])){
                $password = get_safe_replace($_POST['password']);
            }
            else{
                $password = substr($mobile, -6);
            }
            $username = $mobile;
            $data=array();
            $data['username']= $username;
            $data['email']=$email;
            $data['groupid']=6;
            //$data['nickname']=$nickn[0];
            $data['mobile']=$mobile;
            $data['login_count']=1;
            $data['createtime']=time();
            $data['updatetime']=time();
            $data['last_logintime']=time();
            $data['reg_ip']=get_client_ip();
            $data['status']=1;
            $authInfo['password'] = $data['password'] = sysmd5($password);

            if($r=M("User")->create($data)){
                if(false!==M("User")->add()){
                    $authInfo['id'] = $uid=M("User")->getLastInsID();
                    $authInfo['groupid'] = $ru['role_id']=$data['groupid'];
                    $ru['user_id']=$uid;
                    $roleuser=M('RoleUser');
                    $roleuser->add($ru);
                    $jgsat_auth_key = sysmd5($this->sysConfig['ADMIN_ACCESS'].$_SERVER['HTTP_USER_AGENT']);
                    $jgsat_auth = authcode($authInfo['id']."-".$authInfo['groupid']."-".$authInfo['password'], 'ENCODE', $jgsat_auth_key);
                    $authInfo['username'] = $data['username'];
                    $authInfo['email'] = $data['email'];
                    cookie('auth',$jgsat_auth,$cookietime);
                    cookie('username',$authInfo['username'],$cookietime);
                    cookie('groupid',$authInfo['groupid'],$cookietime);
                    cookie('userid',$authInfo['id'],$cookietime);
                    cookie('email',$authInfo['email'],$cookietime);
                    $this->_userid=$uid;
                    $this->_username=$username;
                }
                else{
                    $this->error(L('reg_error'));
                }
            }
            else{
                $this->error(M("User")->getError());
            }
        }
        public function pay(){
            if(!$this->_userid){
                /*注册会员*/
                $this->reguser();
            }
		$model = M('Order');
		/* 检查购物车中是否有商品 */
		$cart_count = $this->dao->where("sessionid = '$this->sessionid'")->count();
		if ($cart_count == 0) $this->error ( L('ORDER_NO_PRODUCT'));

		 /* 检查收货人信息是否完整 */
		if($this->Config['use_address']){
			if($this->_userid){
				$address = M('User_address')->where("userid='$this->_userid' AND isdefault='1' ")->find();
			}else{
				$address = unserialize( cookie('guest_address'));
			}
			if(!$address['province'] || !$address['city'] || !$address['area'] || !$address['address'] || !$address['consignee'] || !$address['mobile']){
				$this->assign('jumpUrl',URL('Home-Order/checkout'));
				$this->error ( L('SHIPPING_ADDRESS_NO_FULL'));
			}
		}else{
			$address=$_POST;
		}

		$order=array();
		/*商品金额*/
		$cart = $this->dao->where("sessionid='{$this->sessionid}'")->select();
		$amount=0;
		foreach($cart as $key=>$r)	$amount = $amount+$r['price'];


		
		$order['amount'] = $amount;
	
		$order['order_amount'] = $order['amount'];
		
		$order['order_amount'] = $order['order_amount']+$order['pay_fee'];
	
		$order['userid'] = intval($this->_userid);
		$order['status'] = 0;
		$order['pay_status']= 0;
		$order['shipping_status']= 0;

		$order['consignee'] = $address['consignee'];
		$order['country'] =  intval($address['country']);
		$order['province']  =  intval($address['province']);
		$order['city'] =  intval($address['city']);
		$order['area'] =  intval($address['area']);
		$order['address'] =  $address['address'];
		//$order['zipcode'] =  $address['zipcode'];
		//$order['tel'] =  $address['tel'];
		$order['mobile'] =  $address['mobile'];
		$order['email'] =  $address['email'];

		$order['add_time'] =  time();
		foreach($order as $key=>$r){if($r==null)$order[$key]='';}
		$orderid= $model->add($order);
		if($orderid){
			$order['sn'] = date("Ymd"). sprintf('%06d',$orderid); 
			$model->save(array('id'=>$orderid,'sn'=>$order['sn']));
                        $order['id']=$orderid;
			foreach($cart as $key=>$r){
				$cart[$key]['order_id']=$orderid;
				$cart[$key]['userid']=$this->_userid;
				M('Order_data')->add($cart[$key]);
			}
			$this->dao->where("sessionid = '$this->sessionid'")->delete();			
		}

		$payment = M('Payment')->field('*')->where("status=1")->select();
                $this->assign('payment',$payment);
		$this->assign('order',$order);
		$this->assign('cart',$cart);
		$this->display();
	}
	public function done(){
            /*支付方式*/
            $orderid= intval($_POST['orderid']);
            $paymentid= intval($_POST['paytype']);
            $Payment = M('Payment')->find($paymentid);
            $data=array();
            $data['id']=$orderid;
            $data['pay_id'] =  intval($Payment['id']);
            $data['pay_name'] =  $Payment['pay_name'] ? $Payment['pay_name'] : '';
            $data['pay_code'] =  $Payment['pay_code'] ? $Payment['pay_code'] : '';
            M('Order')->save($data);
            
            $order = M('Order')->find($orderid);
            $pay_code = $data['pay_code'];
            $aliapy_config = unserialize($Payment['pay_config']);
            $aliapy_config['order_sn']= $order['sn'];
            $aliapy_config['order_amount']= $order['order_amount'];
            $aliapy_config['body'] = $order['consignee'].' '.$order['postmessage'];
            import("@.Pay.".$pay_code);
            $pay=new $pay_code($aliapy_config);
            $paybutton = $pay->get_code();
            header("location: ".$paybutton);
            exit;
	}
        public function respond()
	{
		$pay_code = !empty($_REQUEST['code']) ? get_safe_replace($_REQUEST['code']) : '';	
		$pay_code = ucfirst($pay_code);
		$Payment = M('Payment')->getByPayCode($pay_code);
		if(empty($Payment))$this->error(L('PAY CODE EROOR!'));
		$aliapy_config = unserialize($Payment['pay_config']);		 
		import("@.Pay.".$pay_code);
		$pay=new $pay_code($aliapy_config);
		$r = $pay->respond();	
		
		if($r){
			if (!empty($_POST))
                        {
                            foreach($_POST as $key => $data)
                            {
                                $_GET[$key] = $data;
                            }
                        }
                        $order_sn = trim($_GET['out_trade_no']);
                        $order=M("Order")->where("sn='".$order_sn."'")->find();
                        $this->assign('order',$order);
		}else{
                    $this->assign('jumpUrl',URL('User-Order/index'));
                    $this->error(L('PAY_FAIL'));
		}
                $this->display();
	}
        
	public function postmessage(){
            /*支付方式*/
            $orderid= intval($_POST['orderid']);
            $data=array();
            $data['id']=$orderid;
            $data['postmessage'] =  get_safe_replace($_POST['postmessage']);
            $r=M('Order')->save($data);
            if($r){
                $this->assign('jumpUrl',URL('User-Order/index'));
                $this->error("贺卡祝福提交成功！");
            }
            else{
                $this->error("提交失败!");
            }
	}
}


?>